java计算字符串中最高数字的数量
我试图输出用户输入中出现最高数字的次数,例如用户输入2 4 3 4 2 4 0最高数字是4,它出现了3次,不确定如何进行
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String number, last;
System.out.println("Enter an interger (0 ends the input): ");
number = keyboard.nextLine();
last = number.substring(number.length() - 1);
while(!last.equals("0")){
System.out.println("Must end the input with a 0: ");
number = keyboard.nextLine();
last = number.substring(number.length() - 1);
}
String[] array = number.split(" ");
int max = Integer.MIN_VALUE, maxIndex = 0;
int count;
for (int i = 0; i < array.length; i++) {
if (Integer.parseInt(array[i]) > max) {
max = Integer.parseInt(array[i]);
maxIndex = i;
}
}
//String repeat = number.);
System.out.println("The largest number is " + max);
}
# 1 楼答案
其他答案效率较低,因此我将展示suggested solution by David Wallace的代码:
这就是:
输出
如果在很多地方都想这样做,那么可以编写自己的收集器并使用Java8流
下面是收集器的用法:
这是收藏家自己: